package com.xr.org.emp;

import java.util.List;

import com.bstek.dorado.data.*;
import com.bstek.dorado.data.db.DBStatement;
import com.bstek.dorado.data.db.SqlDataset;
import com.bstek.dorado.utils.StringHelper;
import com.bstek.dorado.utils.variant.VariantSet;
import com.bstek.dorado.common.*;
import com.xr.common.CommUtil;

/**
 * subQueryDatasetEmpListener
 */
public class subQueryDatasetEmpListener extends AbstractDatasetListener {
  public boolean beforeLoadData(Dataset dataset)
     throws Exception {
  String sql="",sqlCon="";
  SqlDataset ds = (SqlDataset) dataset;
  String queryId=ds.parameters().getString("QUERY_ID");
  DBStatement dbs = new DBStatement(); 
dbs.setSql("select * from emp_query_sql where emp_query_id="+queryId+" order by sx");
  List cl=dbs.queryForList();
  for(int i=0;i<cl.size();i++){
	  VariantSet vs=(VariantSet)cl.get(i);
	  //System.out.println("=========="+vs.getString("COLUMN_TYPE"));
	  sqlCon+=""+toChar(vs.getString("LEFT_BRACKET"))+" exists(select 1 from "+vs.getString("table_name")+
	  " where emp.employee_id="+vs.getString("table_name")+".employee_id and ";
	  if(StringHelper.toValidString(vs.getString("COLUMN_TYPE")).equalsIgnoreCase("date")){
		  sqlCon+=""+vs.getString("table_name")+"."+vs.getString("field_name")+" "+vs.getString("MATCHAR")+" to_date('"+vs.getString("field_value")+"','yyyy-MM-dd')) ";
	  }else if(StringHelper.toValidString(vs.getString("COLUMN_TYPE")).equalsIgnoreCase("dropdown")){
		  sqlCon+=""+vs.getString("table_name")+"."+vs.getString("field_name")+" "+vs.getString("MATCHAR")+""+vs.getString("field_value")+") ";
	  }else{
		  sqlCon+="nvl("+vs.getString("table_name")+"."+vs.getString("field_name")+",' ') "+vs.getString("MATCHAR")+" '"+vs.getString("field_value")+"') ";
	  }
	  sqlCon+=toChar(vs.getString("RIGHT_BRACKET"))+" "+toChar(vs.getString("LOGICHAR"))+" ";
  }
  
 // sql="select 1 from org_employee emp where "+sqlCon;
  if(sqlCon.equals("")){
	  sqlCon=" 1=1";
  }
  sql="select * from org_employee emp where 1=1 and "+sqlCon;
  sql += CommUtil.setConditionSQL(ds);
  ds.setSql(sql);
  return true;
  }
  
private String toChar(String d){
	if(d==null){
		return "";
	}else{
		return d;
	}
}
}
